import 'dart:ui';

import 'package:dio/dio.dart';
import 'package:flutter/services.dart';
import 'package:flutter_juwo/common/common_index.dart';
import 'package:flutter/material.dart';
import 'package:flutter_juwo/provider/UserModel.dart';
import 'package:flutter_juwo/ui/custom/LoadingDialog.dart';
import 'package:flutter_juwo/ui/model/login_entity.dart';
import 'package:flutter_juwo/ui/res/shared_preferences_keys.dart';
import 'package:flutter_juwo/ui/utils/sp_util.dart';
import 'package:flutter_juwo/ui/utils/toast_utils.dart';
import 'package:flutter_juwo/ui/utils/utils.dart';
import 'package:provider/provider.dart';

class Login extends StatefulWidget {
  @override
  _LoginState createState() => _LoginState();
}

class _LoginState extends State<Login> {
  int line1Color = 0xFFe5e5e5;
  int line2Color = 0xFFe5e5e5;

  TextEditingController _name =
      TextEditingController(text: SpUtil.getString(SpKeys.userPhone));
  TextEditingController _pass = TextEditingController();

  FocusNode _nameFocusNode, _pwdFocusNode;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _nameFocusNode = FocusNode();
    _nameFocusNode.addListener(() {
      if (_nameFocusNode.hasFocus) {
        setState(() {
          line1Color = 0xFFdf3033;
          line2Color = 0xFFe5e5e5;
        });
      }
    });
    _pwdFocusNode = FocusNode();

    _pwdFocusNode.addListener(() {
      if (_pwdFocusNode.hasFocus) {
        setState(() {
          line2Color = 0xFFdf3033;
          line1Color = 0xFFe5e5e5;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: ListView(
        children: <Widget>[
          ///x
          getRow1(),

          ///登录
          getRow2(),

          ///还没有账号，立即登录
          //  getRow3(),

          ///输入手机号
          getRow4(),
          getLine1(),

          ///输入密码
          getRow5(),
          getLine2(),

          getButton(),
          getBottom(),
        ],
      ),
    );
  }

  getRow1() {
    return Container(
      alignment: Alignment.centerLeft,
      margin: EdgeInsets.fromLTRB(ScreenUtil().setWidth(30),
          MediaQueryData.fromWindow(window).padding.top, 0, 0),
      height: ScreenUtil().setWidth(88),
      child: InkWell(
        onTap: () {
          Application.router.pop(context);
        },
        child: Container(
          padding: EdgeInsets.all(ScreenUtil().setWidth(30)),
          color: Colors.white,
          child: Image.asset(
            Utils.getImgPath("icon_delete"),
            width: ScreenUtil().setWidth(32),
            height: ScreenUtil().setWidth(32),
          ),
        ),
      ),
    );
  }

  getRow2() {
    return Container(
      margin: EdgeInsets.fromLTRB(
          ScreenUtil().setWidth(92), ScreenUtil().setWidth(88), 0, 0),
      alignment: Alignment.centerLeft,
      child: Stack(
        alignment: Alignment.bottomCenter,
        children: <Widget>[
          Container(
            margin: EdgeInsets.only(bottom: ScreenUtil().setWidth(10)),
            height: ScreenUtil().setWidth(14),
            width: ScreenUtil().setWidth(100),
            color: Color(0xFFdf3033),
          ),
          Text(
            "登录",
            style: TextStyle(
              fontSize: ScreenUtil().setWidth(48),
              color: Colours.appC1,
              fontFamily: Font.PingFangBlod,
            ),
            /*TextStyles.custom(48, Colours.appC1, AppFontFamily.PingFangBlod)*/
          ),
        ],
      ),
    );
  }

  getRow4() {
    return Container(
        margin: EdgeInsets.fromLTRB(ScreenUtil().setWidth(90),
            ScreenUtil().setWidth(90), ScreenUtil().setWidth(90), 0),
        child: TextField(
          style: TextStyles.textFiled,
          controller: _name,
          keyboardType: TextInputType.phone,
          inputFormatters: <TextInputFormatter>[
            WhitelistingTextInputFormatter.digitsOnly, //只输入数字
            LengthLimitingTextInputFormatter(11) //限制长度
          ],
          focusNode: _nameFocusNode,
          decoration: InputDecoration(
            hintText: "请输入手机号",
            hintStyle: TextStyles.custom(
                28, Color(0xFF999999), Font.PingFangMedium),
            border: InputBorder.none,
          ),
        ));
  }

  getLine1() {
    return Container(
      margin: EdgeInsets.fromLTRB(
          ScreenUtil().setWidth(90), 0, ScreenUtil().setWidth(90), 0),
      width: ScreenUtil().setWidth(750),
      color: Color(line1Color),
      height: ScreenUtil().setWidth(1),
    );
  }

  getLine2() {
    return Container(
      margin: EdgeInsets.fromLTRB(
          ScreenUtil().setWidth(90), 0, ScreenUtil().setWidth(90), 0),
      width: ScreenUtil().setWidth(750),
      color: Color(line2Color),
      height: ScreenUtil().setWidth(1),
    );
  }

  getRow5() {
    return Container(
      margin: EdgeInsets.fromLTRB(ScreenUtil().setWidth(90),
          ScreenUtil().setWidth(10), ScreenUtil().setWidth(90), 0),
      child: TextField(
        controller: _pass,
        focusNode: _pwdFocusNode,
        style: TextStyles.textFiled,
        obscureText: true,
        decoration: InputDecoration(
          hintText: "请输入密码",
          hintStyle: TextStyles.custom(
              28, Color(0xFF999999), Font.PingFangMedium),
          border: InputBorder.none,
        ),
      ),
    );
  }

  getButton() {
    return Container(
      margin: EdgeInsets.fromLTRB(ScreenUtil().setWidth(56),
          ScreenUtil().setWidth(138), ScreenUtil().setWidth(56), 0),
      child: Consumer<UserModel>(
        builder: (context, UserModel userModel, child) =>
            UiUtils.bottomBotton("登录", () {
          if (isTrueInput()) {
            //开始登录
            showDialog(
                context: context,
                barrierDismissible: false,
                builder: (BuildContext context) {
                  return new LoadingDialog(
                    text: "登录中…",
                  );
                });

            _login(userModel);
          }
        }),
      ),
    );
  }

  getBottom() {
    return Container(
      margin: EdgeInsets.fromLTRB(ScreenUtil().setWidth(90),
          ScreenUtil().setWidth(30), ScreenUtil().setWidth(90), 0),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          GestureDetector(
            onTap: () {
              NavigatorUtils.push(context, "${Routes.register}?type=2",
                  replace: true);
            },
            child: Text(
              "找回密码",
              style: TextStyles.custom(
                  24, Color(0xFF999999), Font.PingFangMedium),
            ),
          ),
          GestureDetector(
            onTap: () {
              NavigatorUtils.push(context, "${Routes.register}?type=1",
                  replace: true);
            },
            child: Text(
              "验证码登录/注册",
              style: TextStyles.custom(
                  24, Colours.appC11, Font.PingFangMedium),
            ),
          )
        ],
      ),
    );
  }

  bool isTrueInput() {
    if (_name.text.length != 11) {
      ToastUtil.showShortErrToast("请输入正确的手机号！");
      return false;
    }

    if (_pass.text.isEmpty) {
      ToastUtil.showShortErrToast("请输入密码！");
      return false;
    }

    return true;
  }

  Future _login(UserModel userModel) async {
    //17099298919  bin110123
    FormData params =
        FormData.from({"name": _name.text, "password": _pass.text});
    DioManager.getInstance().post(Api.LOGIN, params,
        //正常回调
        (data) {
      LoginEntity loginEntity = LoginEntity.fromJson(data);
      if (loginEntity.code == 200) {
        ///保存 token 、手机号
        SpUtil.putString(SpKeys.userToken, loginEntity.data.token);
        SpUtil.putString(SpKeys.userPhone, _name.text);

        userModel.updateToken(loginEntity.data.token);
        setState(() {
          //跳转到相应页面
          Navigator.pop(context);
        });

        ToastUtil.showShortToast(loginEntity.message);
      } else if (loginEntity.code == 400) {
        ToastUtil.showShortErrToast(loginEntity.message);
      } else {
        ToastUtil.showShortErrToast(Api.ERR_NOTHING);
      }
      Navigator.pop(context);
    },
        //错误回调
        (error) {
      ToastUtil.showShortErrToast(Api.ERR_TIME_OUT);
      Navigator.pop(context);
    }, isToken: false);
  }
}
